package com.bigbird.bio;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * 更清晰的封装
 * Boss和 Worker模型
 */
public class BioServerV3 {

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket();
        serverSocket.bind(new InetSocketAddress(1881));
        new Thread(new Boss(serverSocket)).start();
    }

    public static class Boss implements Runnable {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        ServerSocket serverSocket;
        public Boss(ServerSocket serverSocket) {
            this.serverSocket = serverSocket;
        }

        @Override
        public void run() {
            while (true) {
                Socket accept;
                try {
                    accept = serverSocket.accept();
                    OutputStream outputStream = accept.getOutputStream();
                    outputStream.write("hello connection".getBytes(UTF_8));
                    executorService.submit(new Worker(accept));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public static class Worker implements Runnable {
        Socket socket;
        OutputStream outputStream;

        InputStream inputStream;

        public Worker(Socket socket){
            this.socket = socket;
            try {
                this.outputStream=socket.getOutputStream();
                this.inputStream=socket.getInputStream();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public void run() {
            while (true) {
                try {
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    String a;
                    //这个 InputStream的实现是SocketInputStream 此行代码readLine是同步阻塞形代码 当有客户端输入数据进来时，才会继续执行下面的代码
                    while((a=bufferedReader.readLine())!=null){
                        System.out.println(a);
                        OutputStream outputStream = socket.getOutputStream();
                        outputStream.write((a +"_back").getBytes(UTF_8));
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
